<?php

class DB {
	var $host;
	var $port;
	var $user;
	var $pass;
	var $db;
	var $link;
	
	function DB($host, $port, $user, $pass, $db) {
		$this->host = $host;
		$this->port = $port;
		$this->user = $user;
		$this->pass = $pass;
		$this->db = $db;
	}
	
	function connect() {
		$link = & mysql_connect($this->host . ":" . $this->port, $this->user, $this->pass);
		if ($link) {
			$selected = mysql_select_db($this->db, $link);
			if ($selected) {
				$this->link = & $link;
				return true;
			} else {
				$this->link = false;
				return false;
			}
		} else {
			$this->link = false;
			die("can not connect to mysql");
		}
	}
	
	function query() {
		$args = func_get_args();
		$sql = array_shift($args);
		return $this->vquery($sql, $args);
	}
	
	function escape($str) {
		if (!$this->link) {
			$this->connect();
		}
		return mysql_real_escape_string($str);
	}
	
	function vquery($sql, $args) {
		if (!$this->link) {
			$this->connect();
		}
		$args = array_map('db_escape', $args);
		$sql = vsprintf($sql, $args);
		error_log("sql: " . $sql);
		return mysql_query($sql, $this->link);
	}
	
	function close() {
		if ($this->link) {
			mysql_close($this->link);
			$this->link = false;
		}
	}
	
	function insert_id() {
		return mysql_insert_id($this->link);
	}
	
	function affected_rows() {
		return mysql_affected_rows($this->link);
	}
	
	function fetch_assoc($result) {
		return mysql_fetch_assoc($result);
	}
	
	function fetch_row($result) {
		return mysql_fetch_row($result);
	}
}

function db_escape($str) {
	global $db;
	return $db->escape($str);
}